// src/store/index.js
import { createStore } from 'vuex'
import axios from 'axios'

interface State {
  appTheme: 'light' | 'dark';
  articles: any[];
  categories: any[];
  tags: any[];
  user: any | null;
}

const store =  createStore({
  state: {
    articles: [],
    categories: [],
    tags: [],
    user: null,
    appTheme: 'light',
  },
  mutations: {
    SET_ARTICLES(state:State, articles:any) {
      state.articles = articles
    },
    SET_CATEGORIES(state:State, categories:any) {
      state.categories = categories
    },
    SET_TAGS(state:State, tags:any) {
      state.tags = tags
    },
    SET_USER(state:State, user:any) {
      state.user = user
    },
    SET_THEME(state:State, appTheme:any) {
      state.appTheme = appTheme
    },
  },
  actions: {
    async fetchArticles({ commit }: any, { category = null, tag = null, page = 1 } = {}) {
      try {
        // 构造查询参数
        const params: any = {}
        if (category) params.category = category
        if (tag) params.tag = tag
        params.page = page
    
        // 发起请求
        const response = await axios.get('/api/articles', { params })
    
        // 解析响应数据
        const articles = response.data.articles || [] // 文章列表
    
        // 提交到 Vuex
        commit('SET_ARTICLES', articles)
      } catch (error) {
        console.error('Failed to fetch articles:', error)
      }
    },
    async fetchCategories({ commit }: any) {
      const response = await axios.get('/api/categories')
      commit('SET_CATEGORIES', response.data)
    },
    async fetchTags({ commit }: any) {
      const response = await axios.get('/api/tags')
      commit('SET_TAGS', response.data)
    },
    toggleTheme({ commit, state }: any) {
      const newTheme = state.appTheme === 'light' ? 'dark' : 'light'
      commit('SET_THEME', newTheme)
    },
  },
  getters: {
    isAuthenticated: (state:State) => !!state.user,
  },
})

export default store;